package com.siao.util;

import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * @author SiaoLeon
 * 字节数组压缩工具
 */
public class Zlib {

	private static final int CACHE_SIZE = 1024;

	/**
	 * 压缩字节数组
	 * @param bytes
	 * @return
	 * @throws Exception
	 */
	public static final byte[] compress(byte[] bytes) throws Exception {
		Deflater compresser = new Deflater();
		compresser.reset();
		compresser.setInput(bytes);
		compresser.finish();

		byte output[] = new byte[0];
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);

		byte[] buf = new byte[CACHE_SIZE];
		int got;
		while (!compresser.finished()) {
			got = compresser.deflate(buf);
			baos.write(buf, 0, got);
		}

		output = baos.toByteArray();
		baos.close();

		return output;
	}

	/**
	 * 解压缩字节数组
	 * @param bytes
	 * @return
	 * @throws Exception
	 */
	public static final byte[] uncompress(byte[] bytes) throws Exception {
		Inflater decompresser = new Inflater();
		decompresser.reset();
		decompresser.setInput(bytes);

		byte output[] = new byte[0];
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);

		byte[] buf = new byte[CACHE_SIZE];
		int got;
		while (!decompresser.finished()) {
			got = decompresser.inflate(buf);
			baos.write(buf, 0, got);
		}

		output = baos.toByteArray();
		baos.close();

		return output;
	}

}
